// src/utils/User.js

import {UserProfileApi} from "@/api/new/userProfleApi.js";

class UserUtil {
    /**
     * 检查用户是否已登录（通过检查 localStorage 中的 token）
     * @returns {boolean} - 如果有 token 则返回 true，否则返回 false
     */
    static isLogin() {
        return !!localStorage.getItem('drive_platform_token');
    }

    /**
     * 存储用户的 token 到 localStorage
     * @param {string} token - 用户的 token
     */
    static setToken(token) {
        if (token) {
            localStorage.setItem('drive_platform_token', token);
        } else {
            console.warn('设置token不能为空');
        }
    }

    /**
     * 存储用户的 id 到 localStorage
     * @param id
     */
    static setUserId(id) {
        if(id){
            localStorage.setItem('drive_platform_userID', id);
        } else {
            console.warn('设置userid不能为空');
        }
    }

    /**
     *  获取用户的 id
     * @returns {string}
     */
    static getUserId() {
        const userID = localStorage.getItem('drive_platform_userID');
        return userID;
    }


    static async login(username, password) {
        try {
            const res = await UserProfileApi.login(username, password);
            if(typeof res === "string"){
                console.log('登录错误',res);
                return res
            }
            this.setUserId(res.user.userID);
            console.log('设置userID',res.user.userID);
            this.setToken(res.token);
            return res;
        } catch (error) {
            console.error('Login failed:', error);
            throw error;
        }
    }

    static async getUserInfo(userid = this.getUserId()){
        const res = await UserProfileApi.getUserInfo(userid);
        console.log('UserUtil 获取到用户信息',res)
        return res;
    }

    static logout() {
        localStorage.removeItem('drive_platform_token');
        localStorage.removeItem('drive_platform_userID');
    }

    static async register(username, password, email) {
        return await UserProfileApi.register(username, password, email);
    }

    static uploadAvatar() {}
}

export default UserUtil;
